package top.cyixlq.chat

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View.OnFocusChangeListener
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatEditText
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import top.cyixlq.chat.entity.MessageBean
import top.cyixlq.chat.utils.IPUtil
import top.cyixlq.chat.utils.SocketManager
import top.cyixlq.chat.view.ChatMessageAdapter

class MainActivity : AppCompatActivity() {

    private var isServer: Boolean = false
    private lateinit var rvMessage: RecyclerView
    private lateinit var edtMessage: AppCompatEditText
    private lateinit var adapter: ChatMessageAdapter
    private lateinit var nickName: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "聊天"
        nickName = intent.getStringExtra("nickName") ?: IPUtil.getIPAddress(this)
        val type = intent.getIntExtra("type", TYPE_SERVER)
        isServer = type == TYPE_SERVER
        if (isServer) {
            SocketManager.startServer(this, nickName)
            showIpInfoDialog()
        } else {
            showIpInputDialog()
        }
        initView()
        SocketManager.setOnMessageListener {
            adapter.addData(it)
            rvMessage.scrollToPosition(adapter.itemCount - 1)
        }
    }

    private fun initView() {
        adapter = ChatMessageAdapter()
        rvMessage = findViewById(R.id.rvMessage)
        rvMessage.adapter = adapter
        edtMessage = findViewById(R.id.edtMessage)
        edtMessage.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                send()
                return@setOnEditorActionListener true
            }
            false
        }
        edtMessage.onFocusChangeListener = OnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                rvMessage.scrollToPosition(adapter.itemCount - 1)
            }
        }
        findViewById<Button>(R.id.btnSend).setOnClickListener { send() }
    }

    private fun send() {
        val msg = edtMessage.text.toString()
        if (msg.isEmpty()) {
            toastShort("请不要发送空内容")
            return
        }
        if (isServer)
            SocketManager.serverSendMsg(msg)
        else
            SocketManager.sendToServer(msg)
        adapter.addData(MessageBean(false, msg, nickName))
        edtMessage.setText("")
        rvMessage.scrollToPosition(adapter.itemCount - 1)
    }

    @Suppress("SameParameterValue")
    private fun toastShort(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }


    private fun showIpInfoDialog() {
        AlertDialog.Builder(this)
                .setTitle("帮助")
                .setMessage("你已经作为服务端启动，你的ip为：" + IPUtil.getIPAddress(this))
                .setCancelable(false)
                .setPositiveButton("知道了", null)
                .show()
    }

    private fun showIpInputDialog() {
        val editText = AppCompatEditText(this)
        editText.hint = "请输入服务端的ip地址"
        AlertDialog.Builder(this)
                .setTitle("连接到服务端")
                .setView(editText)
                .setCancelable(false)
                .setNeutralButton("取消", null)
                .setPositiveButton("连接") { _, _ ->
                    SocketManager.connectServer(
                            editText.text.toString().trim(),
                            this,
                            nickName
                    )
                }.show()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.help) {
            if (isServer) showIpInfoDialog() else showIpInputDialog()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onDestroy() {
        super.onDestroy()
        SocketManager.release()
    }

    companion object {
        const val TYPE_CLIENT = 1
        const val TYPE_SERVER = 2
        fun start(activity: FragmentActivity, type: Int, nickName: String?) {
            activity.startActivity(
                    Intent(activity, MainActivity::class.java)
                            .putExtra("type", type)
                            .putExtra("nickName", nickName)
            )
        }
    }
}